import base64
import socket
from bottle import get, post, request, run

def check_login(name, password):
    name = name + '\n'
    password = base64.b64encode(password) + '\n' # Actual encryption goes here.
    users_file = open('users.txt', 'r')
    users_list = users_file.readlines()
    users_file.close()
    try:
        password_index = users_list.index(name) + 1
    except:
        return False
    if password == users_list[password_index]:
        return True
    else:
        return False
            

@get('/login')
def login_form():
    return '''<form method="POST">
                <input name="name"     type="text" />
                <input name="password" type="password" />
                <BUTTON name="submit" value="submit" type="submit">
                    Send</BUTTON>
              </form>'''

@post('/login')
def login_submit():
    name = request.forms.get('name')
    password = request.forms.get('password')
    if check_login(name, password):
        return "<p>Your login was correct</p>"
    else:
        return "<p>Login failed</p>"

@get('/reg')
def reg_form():
    return '''<form method="POST">
                <input name="name"     type="text" />
                <input name="password" type="password" />
                <BUTTON name="submit" value="submit" type="submit">
                    Send</BUTTON>
              </form>'''

@post('/reg')
def reg_submit():
    name = request.forms.get('name')
    password = request.forms.get('password')
    name = name + '\n'
    password = base64.b64encode(password) + '\n' # Actual encryption goes here.
    users_file = open('users.txt', 'r')
    users_list = users_file.readlines()
    users_file.close()
    try:
        users_list.index(name)
    except:
        users_file = open('users.txt', 'a')
        users_file.write(name)
        users_file.write(password)
        return "<p>User name and password registered</p>"
    return "<p>User name already exists</p>"

run(host=socket.gethostbyname(socket.gethostname()))
